<template>
  <view class="page">
    <!-- 顶部标题 -->
    <view class="header">
      <text class="title">{{ mode==='deliver' ? '取车地点' : '还车地点' }}</text>
    </view>

    <!-- 搜索 + 重新定位 -->
    <view class="search-row">
      <input class="search"
             v-model="keyword"
             placeholder="请输入 站点名/地址 关键字"
             confirm-type="search"
             @focus="showDropdown = true"
             @input="onInput"
             @confirm="onSearch"/>
      <view class="regeo" @tap="reLocate">重新定位</view>
    </view>

    <!-- 搜索结果下拉 -->
    <view v-if="showDropdown && keywordTrim.length" class="search-panel">
      <view v-if="filteredStations.length" class="sp-list">
        <view class="sp-item"
              v-for="s in filteredStations"
              :key="s.id"
              @tap="goToStation(s)">
          <view class="sp-name">{{ s.name }}</view>
          <view class="sp-addr">{{ s.address }}</view>
        </view>
      </view>
      <view v-else class="sp-empty">没有匹配的站点</view>
    </view>

    <!-- 当前定位 -->
    <view class="current">
      <view class="current-title">当前位置</view>
      <view class="poi">
        <image class="poi-icon" :src="poiIcon" mode="widthFix"></image>
        <view class="poi-text">
          <text class="poi-name">{{ currentPoiName || '未知位置' }}</text>
          <text class="poi-addr">{{ currentAddress || '' }}</text>
        </view>
      </view>
    </view>

    <!-- 地图 -->
    <view class="map-wrap" @tap="showDropdown=false">
      <map id="pickMap"
           class="map"
           :latitude="center.latitude"
           :longitude="center.longitude"
           :scale="scale"
           :markers="markers"
           :show-location="true"
           @regionchange="onRegionChange"
           @markertap="onMarkerTap"
      />
      <!-- 中心悬浮定位图 -->
      <image class="center-pin" :src="centerIcon" mode="widthFix"></image>
    </view>

    <!-- 底部：只有选中站点才出现 -->
    <view class="bottom">
      <button v-if="selectedMarker" class="btn primary" @tap="confirmMarker">选择此站点</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      mode: 'deliver',

      // 图标
      centerIcon: 'https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/location.png',
      poiIcon:    'https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/location.png',

      // 搜索
      keyword: '',
      showDropdown: false,

      // 地图中心/缩放
      center: { latitude: 24.482, longitude: 118.096 },
      scale: 16,

      // 当前位置信息（可接入逆地理完善）
      currentPoiName: '万达广场',
      currentAddress: '福建省厦门市湖里区万达广场',

      // 示例站点（可自行增减）
      stations: [
        { id: 1, name: '万达广场·A站',  lat: 24.486, lng: 118.100, address: '湖里区万达广场A座门口' },
        { id: 2, name: '软件园·B站',    lat: 24.488, lng: 118.120, address: '思明区软件园二期西门' },
        { id: 3, name: '火车站·C站',    lat: 24.468, lng: 118.121, address: '厦门火车站北广场' },
        { id: 4, name: '中山路·D站',    lat: 24.453, lng: 118.082, address: '思明区中山路步行街口' },
        { id: 5, name: '五缘湾·E站',    lat: 24.510, lng: 118.153, address: '湖里区五缘湾乐都汇' },
        { id: 6, name: '机场T4·F站',    lat: 24.544, lng: 118.129, address: '翔安机场T4到达层' },
        { id: 7, name: '观音山·G站',    lat: 24.493, lng: 118.191, address: '观音山商务区公交站旁' },
        { id: 8, name: '集美学村·H站',  lat: 24.582, lng: 118.095, address: '学村地铁站B口' }
      ],
      markers: [],
      selectedMarker: null,
      opener: null
    }
  },
  computed:{
    keywordTrim(){ return (this.keyword || '').trim(); },
    filteredStations(){
      const kw = this.keywordTrim.toLowerCase();
      if(!kw) return [];
      return this.stations.filter(s =>
        s.name.toLowerCase().includes(kw) ||
        (s.address && s.address.toLowerCase().includes(kw))
      ).slice(0, 20);
    }
  },
  onLoad(query){
    this.mode = query.mode || 'deliver';
    const ec = this.getOpenerEventChannel && this.getOpenerEventChannel();
    this.opener = ec;
    ec && ec.on && ec.on('init', (payload)=>{ /* 可用 selectedId 高亮 */ });
    this.toMarkers();      // 初始 markers
    this.getMyLocation();  // 定位中心
  },
  methods:{
    // 构造 markers；selectedId 有值时，让该 marker 的 callout 高亮且常显
    toMarkers(selectedId = this.selectedMarker?.id){
      const selectedColor = '#0a67b8';
      this.markers = this.stations.map(s=>{
        const isSel = selectedId === s.id;
        return {
          id: s.id,
          latitude: s.lat,
          longitude: s.lng,
          width: 28, height: 28,
          callout: {
            content: s.name,
            color: '#ffffff',
            fontSize: 12,
            borderRadius: 6,
            padding: 6,
            bgColor: isSel ? selectedColor : '#7f8c8d',
            display: isSel ? 'ALWAYS' : 'BYCLICK'
          }
        }
      });
    },

    async getMyLocation(){
      try{
        const res = await uni.getLocation({ type: 'gcj02' });
        const lat = res[1]?.latitude || res.latitude;
        const lng = res[1]?.longitude || res.longitude;
        this.center = { latitude: lat, longitude: lng };
        this.scale = 16;
      }catch(e){}
    },
    onRegionChange(e){
      if(e.type==='end'){
        const ctx = uni.createMapContext('pickMap', this);
        ctx.getCenterLocation({
          success: (r) => { this.center = { latitude: r.latitude, longitude: r.longitude }; }
        });
      }
    },

    // 点击地图上的 marker：聚焦并显示 callout，高亮该站点
    onMarkerTap(e){
      const id = e.detail.markerId;
      const s = this.stations.find(x=>x.id===id);
      this.selectedMarker = s || null;
      if(s){ this.center = { latitude: s.lat, longitude: s.lng }; }
      this.toMarkers(id);  // 让选中的 callout 常显并改成主题色
    },

    // 搜索交互
    onInput(){ this.showDropdown = true; },
    onSearch(){ this.showDropdown = false; },
    goToStation(s){
      this.selectedMarker = s;
      this.center = { latitude: s.lat, longitude: s.lng };
      this.scale = 17;
      this.toMarkers(s.id);
      this.showDropdown = false;
      // 平移地图到该点
      const ctx = uni.createMapContext('pickMap', this);
      ctx.moveToLocation({ latitude: s.lat, longitude: s.lng });
    },

    reLocate(){ this.getMyLocation(); },

    // 选择站点 -> 回传上一页
    confirmMarker(){
      if(!this.selectedMarker) return;
      const s = this.selectedMarker;
      const station = { id:s.id, name:s.name, address:s.address||'', lat:s.lat, lng:s.lng };
      if(this.opener && this.opener.emit){
        this.opener.emit('pickStation', { mode: this.mode, station });
      }
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss" scoped>
.page{ background:#fff; min-height:100vh; padding-bottom: env(safe-area-inset-bottom); }

/* 标题 */
.header{ padding: 20rpx 24rpx 10rpx; text-align:center; }
.title{ font-size: 36rpx; font-weight: 800; }

/* 搜索行 */
.search-row{ display:flex; align-items:center; gap: 16rpx; padding: 16rpx 24rpx; position: relative; z-index: 5; }
.search{ flex:1; background:#f2f3f5; border-radius: 999rpx; padding: 16rpx 24rpx; font-size: 26rpx; }
.regeo{ color:#0a67b8; font-size: 28rpx; }

/* 搜索下拉 */
.search-panel{
  position: absolute; top: 112rpx; left: 24rpx; right: 24rpx;
  background:#fff; border-radius: 16rpx; box-shadow: 0 12rpx 40rpx rgba(0,0,0,.10);
  max-height: 520rpx; overflow:auto; z-index: 9;
}
.sp-list{ padding: 8rpx 0; }
.sp-item{ padding: 20rpx 24rpx; border-bottom: 1px solid #f0f2f5; }
.sp-item:last-child{ border-bottom: 0; }
.sp-name{ font-size: 30rpx; color:#1f2329; font-weight: 700; }
.sp-addr{ font-size: 24rpx; color:#6c727a; margin-top: 6rpx; }
.sp-empty{ padding: 28rpx; text-align:center; color:#a0a7b1; }

/* 当前位置 */
.current{ padding: 10rpx 24rpx 6rpx; }
.current-title{ font-size: 30rpx; font-weight: 700; margin-bottom: 8rpx; }
.poi{ display:flex; align-items:flex-start; gap: 12rpx; }
.poi-icon{ width: 28rpx; height: 28rpx; margin-top: 6rpx; }
.poi-text .poi-name{ display:block; font-size: 32rpx; margin-bottom: 4rpx; }
.poi-text .poi-addr{ display:block; color:#6c727a; font-size: 26rpx; }

/* 地图与中心图标 */
.map-wrap{ position:relative; margin: 16rpx 24rpx; border-radius: 12rpx; overflow:hidden; height: 900rpx; }
.map{ width:100%; height:100%; }
.center-pin{
  width: 44rpx; height: 44rpx;
  position:absolute; left:50%; top:50%;
  transform: translate(-50%, -80%);
}

/* 底部按钮 */
.bottom{ position:fixed; left:0; right:0; bottom: 24rpx; padding: 0 24rpx; }
.btn{
  width:100%; height: 88rpx; line-height: 88rpx;
  text-align:center; border-radius: 16rpx;
  background:#0a67b8; color:#fff; font-size: 30rpx;
}
.primary{ background:#0a67b8; color:#fff; }
</style>
